package com.siao.starling.display
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObjectContainer;
	
	import starling.display.Image;
	import starling.events.EnterFrameEvent;
	import starling.events.Event;
	import starling.textures.Texture;
	
	/**
	 * 位图元素
	 * @author SiaoLeon
	 */
	public class ImageElement extends Image
	{
		// -------------------------------------------------------------------------------------------------------- 静态常量
		
		// -------------------------------------------------------------------------------------------------------- 静态变量
		
		// -------------------------------------------------------------------------------------------------------- 静态方法
		
		// -------------------------------------------------------------------------------------------------------- 静态函数
		
		// -------------------------------------------------------------------------------------------------------- 属性
		
		private var _target:DisplayObjectContainer
		
		public function get target():DisplayObjectContainer
		{
			return this._target;
		}
		
		public function set target(value:DisplayObjectContainer):void
		{
			this._target = value;
			
			this.redraw();
		}
		
		// -------------------------------------------------------------------------------------------------------- 变量
		
		private var meta:Bitmap;
		
		// -------------------------------------------------------------------------------------------------------- 构造
		
		/**
		 * 构造函数
		 */
		public function ImageElement(target:DisplayObjectContainer)
		{
			super(Texture.empty(1, 1));
			
			this.meta = new Bitmap();
			
			this.target = target;
			this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		}
		
		// -------------------------------------------------------------------------------------------------------- 方法
		
		// -------------------------------------------------------------------------------------------------------- 函数
		
		/**
		 * 重绘
		 */
		protected function redraw():void
		{
			if (this.target == null)
			{
				return;
			}
			
			if (this.stage == null)
			{
				return;
			}
			
			if (this.target.width == 0 || this.target.height == 0)
			{
				return;
			}
			
			if (!this.target.contains(this.meta))
			{
				this.target.addChild(this.meta);
			}
			
			var bitmapData:BitmapData = new BitmapData(this.target.width, this.target.height, true, 0);
			bitmapData.draw(this.target);
			
			this.texture = Texture.fromBitmapData(bitmapData);
			this.readjustSize();
		}
		
		private function onAddedToStage(event:Event):void
		{
			this.addEventListener(EnterFrameEvent.ENTER_FRAME, onEnterFrame);
		}
		
		private function onEnterFrame(event:Event):void
		{
			this.redraw();
		}
	
	}
}
